import { useDebugValue, useState } from "react";

const useCookie = (name: string, init:string = '') => {
  const getCookie = () => {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
    if (match) {
      return decodeURIComponent(match[2]) || init
    }
  }

  const [cookie, setCookie] = useState(getCookie())

  const updateCookie = (value: string) => {
    setCookie(value)
    document.cookie = name + '=' + value
  }

  const deleteCookie = () => {
    setCookie('')
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
  }

  useDebugValue(cookie, (value) => value)

  return [cookie, updateCookie, deleteCookie] as const

}

export default function UseDebugValue () {

  const [cookie, updateCookie, deleteCookie] = useCookie('name', 'value')
  
  return (
    <>
      <h1>useDebugValue</h1>
      <div>cookie: {cookie}</div>
      <div>
        <button onClick={() => updateCookie('123')}>更新cookie</button>
        <button onClick={deleteCookie}>删除cookie</button>
      </div>
    </>
  )
}